import React, { useState,useEffect } from 'react';
import { Table, Input, InputNumber, Popconfirm, Form, Typography } from 'antd';
import './index.css';

import {getAuthList}from '../../../api/auth'

let originData = [];

//权限数据源
 let actions=[
  {
    action: 'query',
    name: '查询列表',
    describe: '查询列表',
  },
  {
    action: 'get',
    name: '查询明细',
    describe: '查询明细',
  },
  {
    action: 'add',
    name: '新增',
    describe: '新增',
  },
  {
    action: 'update',
    name: '修改',
    describe: '修改',
  },
  {
    action: 'delete',
    name: '删除',
    describe: '删除',
  },
  {
    action: 'import',
    name: '导入',
    describe: '导入',
  },
  {
    action: 'export',
    name: '导出',
    describe: '导出',
  },
]

/**
 * 数据
 */
 
// for (let i = 0; i < 100; i++) {
//   originData.push({
//     key: i.toString(),
//     id: `Edrward ${i}`,
//     name: 32,
//     state: `London Park no. ${i}`,
//   });
// }

/**
 * 
 * TODO 
 */


const EditableCell = ({
  editing,
  dataIndex,
  title,
  inputType,
  record,
  index,
  children,
  ...restProps
}) => {
  const inputNode = inputType === 'number' ? <InputNumber /> : <Input />;
  return (
    <td {...restProps}>
      {editing ? (
        <Form.Item
          name={dataIndex}
          style={{
            margin: 0,
          }}
          rules={[
            {
              required: true,
              message: `Please Input ${title}!`,
            },
          ]}
        >
          {inputNode}
        </Form.Item>
      ) : (
        children
      )}
    </td>
  );
}; 

/**
 * 
 * @returns TODO
 */

const EditableTable = (props) => {


 
  const [form] = Form.useForm();
  const [data, setData] = useState(actions);
  const [editingKey, setEditingKey] = useState('');
  let [searchsta,setSearchasta]=useState({id:'',name:''});

  const isEditing = (record) => record.key === editingKey;


  useEffect(()=>{

    let newValue=actions.map((item,index)=>{
      item.key=index+1;

      return item;
    })

    setData(newValue);
  },[])
  
 
  const edit = (record) => {
    form.setFieldsValue({
      ID: '',
      名称: '',
      状态: '',
      ...record,
    });
    setEditingKey(record.key);
  };

  function del(data){

    //直接过滤掉id
    const newData=originData.filter((item)=>{
      if(item.id !== data.id){
        return item;
      }
    
    })
    console.log("过滤后的数据",newData);
    originData=newData;
    setData(newData);
  
  
  
  }

  const cancel = () => {
    setEditingKey('');
  };

  const save = async (key) => {
    try {
      const row = await form.validateFields();
      const newData = [...data];
      const index = newData.findIndex((item) => key === item.key);

      if (index > -1) {
        const item = newData[index];
        newData.splice(index, 1, { ...item, ...row });
        setData(newData);
        setEditingKey('');
      } else {
        newData.push(row);
        setData(newData);
        setEditingKey('');
      }
    } catch (errInfo) {
      console.log('Validate Failed:', errInfo);
    }
  };

  const columns = [
    {
    
      title: '操作类型',
      dataIndex: 'action',
      width: '25%',
      editable: true,
    },
    {
      title: '名称',
      dataIndex: 'name',
      width: '15%',
      editable: true,
    },
    {
      title: '描述',
      dataIndex: 'describe',
      width: '40%',
      editable: true,
    },
    {
      title: '操作',
      dataIndex: 'operation',
      render: (_, record) => {
        const editable = isEditing(record);
        return editable ? (
          <span>
            <a
              href="javascript:;"
              onClick={() => save(record.key)}
              style={{
                marginRight: 8,
              }}
            >
              Save
            </a>
            <Popconfirm title="Sure to cancel?" onConfirm={cancel}>
              <a>Cancel</a>
            </Popconfirm>
          </span>
        ) : (
          <>
           <Typography.Link disabled={editingKey !== ''} onClick={() => edit(record)}>
            Edit
          </Typography.Link>
          <span>&nbsp;&nbsp;</span>
          <Typography.Link onClick={() => del(record)}>
            Del
          </Typography.Link>
          </>
         
          
        );
      },
    },
  ];

  const mergedColumns = columns.map((col) => {
    if (!col.editable) {
      return col;
    }

    return {
      ...col,
      onCell: (record) => ({
        record,
        inputType: col.dataIndex === 'age' ? 'number' : 'text',
        dataIndex: col.dataIndex,
        title: col.title,
        editing: isEditing(record),
      }),
    };
  });
  return (
    <Form form={form} component={false}>
      <Table
        components={{
          body: {
            cell: EditableCell,
          },
        }}
        bordered
        dataSource={data}
        columns={mergedColumns}
        rowClassName="editable-row"
        pagination={{
          onChange: cancel,
        }}
      />
    </Form>
  );
};

export default EditableTable;


